package chu.dejian.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.sam.ble.unimplements.BLEBRHelper;
import com.sam.blemodule.R;
import com.sam.utils.L;
import com.sam.utils.T;
import com.sam.utils.display.DensityUtils;
import com.sam.widget.listview.custom_menu_list.BaseSwipeMenuAdapter;
import com.sam.widget.listview.custom_menu_list.SwipeMenuItemLayout;
import java.util.ArrayList;
import java.util.List;

import chu.dejian.db.DBHelper;
import chu.dejian.entity.ContactEntity;
import chu.dejian.entity.SendedRequestEntity;
import chu.dejian.models.PostAttenderRequestRequest;
import chu.dejian.models.PostAttenderRequestResponse;
import chu.dejian.restApi.RestClient;
import chu.dejian.ui.activity.AttentionApplyActivity;
import chu.dejian.widget.AttentionLevelView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by Administrator on 2016/7/19 0019.
 */
public class SendedRequestAdapter extends BaseSwipeMenuAdapter {
    private List<ContactEntity> requestList;
    private static AttentionLevelView.ATTENTION_LEVEL orignLevel;
    
    public SendedRequestAdapter(List<ContactEntity> requestList) {
        this.requestList = requestList;
    }

    @Override
    public int getCount() {
        return requestList.size();
    }

    @Override
    public ContactEntity getItem(int position) {
        return requestList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getItemContentView(int position, LinearLayout contentParentView, SwipeMenuItemLayout swipeMenuLayout) {
        View itemView = View.inflate(swipeMenuLayout.getContext(),R.layout.row_attention_vertical,null);
        TextView statusTextView = (TextView) itemView.findViewById(R.id.status);
        TextView attentionName = (TextView) itemView.findViewById(R.id.contact_name);
        TextView attentionPhoneNum = (TextView) itemView.findViewById(R.id.contact_num);
        final AttentionLevelView levelView = (AttentionLevelView) itemView.findViewById(R.id.attention_level_view);
        statusTextView.setVisibility(View.VISIBLE);
        Context context = swipeMenuLayout.getContext();
        switch (getItem(position).attentionStatus){
            case SendedRequestEntity.STATUS_TIMEOUT:
                statusTextView.setText(context.getString(R.string.request_timeout));
                statusTextView.setBackgroundResource(R.drawable.d_blue_rounded_bg);

                break;
            case SendedRequestEntity.STATUS_CONSENTED:
                statusTextView.setText(context.getString(R.string.request_consented));
                statusTextView.setBackgroundResource(R.drawable.d_green_rounded_bg);
                break;
            case SendedRequestEntity.STATUS_PENDING:
                statusTextView.setText(context.getString(R.string.request_pending));
                statusTextView.setBackgroundResource(R.drawable.d_orange_rounded_bg);
                break;
            case SendedRequestEntity.STATUS_REFUSED:
                statusTextView.setText(context.getString(R.string.request_refused));
                statusTextView.setBackgroundResource(R.drawable.d_red_rounded_bg);
                break;
        }

        final ContactEntity contactEntity = getItem(position);
        if(contactEntity == null) return itemView;
            attentionName.setText(contactEntity.contactName);
            attentionPhoneNum.setText(contactEntity.contactPhoneNum);
            levelView.setLevel(contactEntity.attentionLevel);
            levelView.setEditable(true);
            levelView.setSpinnerCallBack(new AttentionLevelView.SpinnerCallBack() {
                @Override
                public void onSpinnerOpen() {
                    orignLevel = levelView.getAttentionLevel();
                }

                @Override
                public void onSpinnerClose() {
                    if(orignLevel == levelView.getAttentionLevel()) return;
                    PostAttenderRequestRequest request = new PostAttenderRequestRequest(contactEntity.contactPhoneNum, levelView.getAttentionLevelValue(), contactEntity.contactName);
                    RestClient.getAuthedClient().getApiService().postAttenderRequest(request, new Callback<PostAttenderRequestResponse>() {
                        @Override
                        public void success(PostAttenderRequestResponse postAttenderRequestResponse, Response response) {
                            String requestStr = postAttenderRequestResponse == null ? "null" : postAttenderRequestResponse.toString();
                            L.d("《用户提交关注请求-postAttenderRequest》" + "\n" + "请求成功： \n\t返回数据：" + requestStr);// + "\n\t响应数据：" + printResponse(response));
                            if(response.getStatus() != 201){
                                T.showLong(levelView.getContext(),R.string.level_change_failed);
                                levelView.setLevel(orignLevel);
                            }
                        }

                        @Override
                        public void failure(RetrofitError retrofitError) {
                            L.d("《用户提交关注请求-postAttenderRequest》"+"\n"+ "请求失败： \n\t错误信息：" + retrofitError.toString());
                            T.showLong(levelView.getContext(),R.string.level_change_failed);
                            levelView.setLevel(orignLevel);
                        }
                    });
                }
            });
        return itemView;
    }

    @Override
    public List<View> getItemMenuViews(final int position, LinearLayout menuItemsLayout, SwipeMenuItemLayout swipeMenuLayout) {
        Context context = swipeMenuLayout.getContext();
        List<View> itemMenuViews = new ArrayList<>();
        switch (getItem(position).attentionStatus){
            case SendedRequestEntity.STATUS_TIMEOUT:
                itemMenuViews.add(getItemTextMenu(context,R.color.green_menu_bg_color,R.string.resend));
                itemMenuViews.add(getItemTextMenu(context,R.color.cyan_menu_bg_color,R.string.modify));
                itemMenuViews.add(getItemTextMenu(context,R.color.orange_menu_bg_color,R.string.delete));
                swipeMenuLayout.setOnSwipeMenuItemClickListener(new SwipeMenuItemLayout.OnSwipeMenuItemClickListener() {
                    @Override
                    public void onSwipeMenuItemClicked(SwipeMenuItemLayout swipeMenuLayout, int menuPosition, View menuView) {
                        onMenuItemClick(swipeMenuLayout.getContext(),position,menuPosition);
                    }
                });
                return itemMenuViews;
            case SendedRequestEntity.STATUS_CONSENTED:
                itemMenuViews.add(getItemTextMenu(context,R.color.orange_menu_bg_color,R.string.delete));
                swipeMenuLayout.setOnSwipeMenuItemClickListener(new SwipeMenuItemLayout.OnSwipeMenuItemClickListener() {
                    @Override
                    public void onSwipeMenuItemClicked(SwipeMenuItemLayout swipeMenuLayout, int menuPosition, View menuView) {
                        onMenuItemClick(swipeMenuLayout.getContext(),position,menuPosition+2);
                    }
                });
                return itemMenuViews;
            case SendedRequestEntity.STATUS_PENDING:
                itemMenuViews.add(getItemTextMenu(context,R.color.cyan_menu_bg_color,R.string.modify));
                itemMenuViews.add(getItemTextMenu(context,R.color.orange_menu_bg_color,R.string.delete));
                swipeMenuLayout.setOnSwipeMenuItemClickListener(new SwipeMenuItemLayout.OnSwipeMenuItemClickListener() {
                    @Override
                    public void onSwipeMenuItemClicked(SwipeMenuItemLayout swipeMenuLayout, int menuPosition, View menuView) {
                        onMenuItemClick(swipeMenuLayout.getContext(),position,menuPosition+1);
                    }
                });
                return itemMenuViews;
            case SendedRequestEntity.STATUS_REFUSED:
                itemMenuViews.add(getItemTextMenu(context,R.color.green_menu_bg_color,R.string.resend));
                itemMenuViews.add(getItemTextMenu(context,R.color.cyan_menu_bg_color,R.string.modify));
                itemMenuViews.add(getItemTextMenu(context,R.color.orange_menu_bg_color,R.string.delete));
                swipeMenuLayout.setOnSwipeMenuItemClickListener(new SwipeMenuItemLayout.OnSwipeMenuItemClickListener() {
                    @Override
                    public void onSwipeMenuItemClicked(SwipeMenuItemLayout swipeMenuLayout, int menuPosition, View menuView) {
                        onMenuItemClick(swipeMenuLayout.getContext(),position,menuPosition);
                    }
                });
                return itemMenuViews;
            default: return null;
        }
    }


    private TextView getItemTextMenu(Context context, @DrawableRes int bgColorResId, @StringRes int menuTextResId){
        TextView itemMenu = new TextView(context);
        itemMenu.setLayoutParams(new LinearLayout.LayoutParams(DensityUtils.dp2px(context, 60),LinearLayout.LayoutParams.MATCH_PARENT));
        itemMenu.setGravity(Gravity.CENTER);
        itemMenu.setTextSize(16);
        itemMenu.setTextColor(Color.WHITE);
        itemMenu.setBackgroundResource(bgColorResId);
        itemMenu.setText(menuTextResId);
        return itemMenu;
    }

    public boolean onMenuItemClick(final Context context, final int position, int index) {
        final ContactEntity contactEntity = requestList.get(position);
        switch (index) {
            case 0: //重发
                PostAttenderRequestRequest request = new PostAttenderRequestRequest(contactEntity.contactPhoneNum, contactEntity.attentionLevel.ordinal(), contactEntity.contactName);
                RestClient.getAuthedClient().getApiService().postAttenderRequest(request, new Callback<PostAttenderRequestResponse>() {
                    @Override
                    public void success(PostAttenderRequestResponse postAttenderRequestResponse, Response response) {
                        if(response.getStatus() == 401) {
                            BLEBRHelper.getInstance().sendReloginBR(context);
                            T.showShort(context,R.string.nauthorized_and_relogin);
                            return;
                        }
                        String requestStr = postAttenderRequestResponse == null ? "null" : postAttenderRequestResponse.toString();
                        L.d("《用户提交关注请求-postAttenderRequest》" + "\n" + "请求成功： \n\t返回数据：" + requestStr);// + "\n\t响应数据：" + printResponse(response));
                        if(response.getStatus() == 201) T.showLong(context,R.string.resend_succeeded);
                        else T.showLong(context,R.string.resend_failed);
                    }

                    @Override
                    public void failure(RetrofitError retrofitError) {
                        L.d("《用户提交关注请求-postAttenderRequest》"+"\n"+ "请求失败： \n\t错误信息：" + retrofitError.toString());
                        T.showLong(context,R.string.resend_failed);
                    }
                });
                break;
            case 1: //修改
                Intent intent = new Intent(context,AttentionApplyActivity.class);
                intent.putExtra(AttentionApplyActivity.EXTRA_KEY_CONTACT_NAME, contactEntity.contactName);
                intent.putExtra(AttentionApplyActivity.EXTRA_KEY_CONTACT_PHONE, contactEntity.contactPhoneNum);
                intent.putExtra(AttentionApplyActivity.EXTRA_KEY_CONTACT_LEVEL, contactEntity.attentionLevel == null ? -1 : contactEntity.attentionLevel.ordinal());
                context.startActivity(intent);
                break;
            case 2: //删除
                RestClient.getAuthedClient().getApiService().deleteAttenderRequest(contactEntity.id, new Callback() {
                    @Override
                    public void success(Object o, Response response) {
                        if(response.getStatus() == 401) {
                            BLEBRHelper.getInstance().sendReloginBR(context);
                            T.showShort(context,R.string.nauthorized_and_relogin);
                            return;
                        }
                        L.d("《删除用户提交过的关注请求-postAttenderRequest》" + "\n" + "请求成功： \n\t返回数据：" + response.toString());// + "\n\t响应数据：" + printResponse(response));
                        if(response.getStatus() == 204) {
                            requestList.remove(position);
                            DBHelper.getInstance().getSendedRequestDao().deleteRequest(contactEntity.id);
                            notifyDataSetChanged();
                        } else T.showLong(context,R.string.delete_failed);
                    }

                    @Override
                    public void failure(RetrofitError retrofitError) {
                        L.d("《删除用户提交过的关注请求-postAttenderRequest》"+"\n"+ "请求失败： \n\t错误信息：" + retrofitError.toString());
                        T.showLong(context, R.string.delete_failed);
                    }
                });
                break;
        }
        return false;
    }


}
